package com.myteam.mystory.presention;

import java.util.ArrayList;
import java.util.List;

import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;

import com.myteam.mystory.R;
import com.myteam.mystory.adapter.MenuLeftAdapter;
import com.myteam.mystory.entity.AuthorEntity;
import com.myteam.mystory.entity.CategoryEntity;
import com.myteam.mystory.entity.ChapterEntity;
import com.myteam.mystory.entity.ParamEntity;
import com.myteam.mystory.entity.StoriesEntity;
import com.myteam.mystory.fragment.AllStoryFragment;
import com.myteam.mystory.fragment.BookmarkFragment;
import com.myteam.mystory.fragment.HistoryFragment;
import com.myteam.mystory.fragment.TopViewFragment;
import com.myteam.mystory.service.AuthorService;
import com.myteam.mystory.service.CategoriesService;
import com.myteam.mystory.service.ChapterService;
import com.myteam.mystory.service.ParamService;
import com.myteam.mystory.service.StoriesService;
import com.myteam.mystory.utils.LogUtils;
//import com.myteam.mystory.adapter.MenuLeftAdapter;


public class MainActivity extends FragmentActivity implements OnClickListener, OnItemClickListener {
	private Context context;
	private LinearLayout left_drawer_root;
	private DrawerLayout mDrawerLayout;
	private ListView menuLeftList;
	private ViewPager viewpager;
	private ActionBarDrawerToggle mDrawerToggle;
//	private LinearLayout list_text_search;
	
	private AllStoryFragment allStoryFragment;
	private BookmarkFragment bookmarkFragment;
	private HistoryFragment historyFragment;
	private TopViewFragment topViewFragment;
	
	private View all_story;
	private View top_view;
	private View bookmark;
	private View history;
	
	private FrameLayout all_story_root;
	private FrameLayout top_view_root;
	private FrameLayout bookmark_root;
	private FrameLayout history_root;
	
	private static final int TAB_ALL_STORY = 0;
	private static final int TAB_TOP_VIEW = 1;
	private static final int TAB_BOOKMARK = 2;
	private static final int TAB_HISTORY = 3;
	
	private int onPageSelected = 0;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		context = this;
		initView();
		testDB();
//		deleteTableDB();
		getActionBar().setIcon(R.drawable.ic_launcher);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_actionbar_title));
		
		viewpager.setAdapter(new StoryPagerAdapter(getSupportFragmentManager()));
		viewpager.setOffscreenPageLimit(4);
		viewpager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int pos) {
				showViewpagerTab(pos);
				onPageSelected = pos;
			}
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {}
			@Override
			public void onPageScrollStateChanged(int arg0) {}
		});
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_launcher, R.string.app_name, R.string.app_name){
			public void onDrawerClosed(View view) {  /*sliding menu dua vao */}
			public void onDrawerOpened(View drawerView) {/*sliding menu keo ra*/}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);
		CategoriesService categoriesService = new CategoriesService(context);
		List<String> arr_CateName = categoriesService.getCateName();
		MenuLeftAdapter adapter = new MenuLeftAdapter(context, R.id.menuleft_cateName, arr_CateName);
		menuLeftList.setAdapter(adapter);
		menuLeftList.setOnItemClickListener(this);
		
//		LoadingData load = new LoadingData(MainActivity.this);
//		load.execute();
	}
	
	private void initView(){
		left_drawer_root = (LinearLayout) findViewById(R.id.left_drawer_root);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		menuLeftList = (ListView) findViewById(R.id.left_drawer);
		viewpager = (ViewPager) findViewById(R.id.activity_main_viewpager);
		all_story = (View) findViewById(R.id.activity_main_all_story);
		top_view = (View) findViewById(R.id.activity_main_top_view);
		bookmark = (View) findViewById(R.id.activity_main_bookmark);
		history = (View) findViewById(R.id.activity_main_history);
		all_story_root = (FrameLayout) findViewById(R.id.activity_main_all_root);
		top_view_root = (FrameLayout) findViewById(R.id.activity_main_author_root);
		bookmark_root = (FrameLayout) findViewById(R.id.activity_main_bookmark_root);
		history_root = (FrameLayout) findViewById(R.id.activity_main_history_root);
		all_story_root.setOnClickListener(this);
		top_view_root.setOnClickListener(this);
		bookmark_root.setOnClickListener(this);
		history_root.setOnClickListener(this);
		allStoryFragment = new AllStoryFragment();
		bookmarkFragment = new BookmarkFragment(context);
		historyFragment = new HistoryFragment(context);
		topViewFragment = new TopViewFragment();
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {   //click vao icon app tren ActionBar
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		switch (item.getItemId()) {
		case R.id.action_settings:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = new MenuInflater(this);
		inflater.inflate(R.menu.theme_wallpaper_menu, menu);
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
		searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
		searchView.setOnQueryTextListener(new OnQueryTextListener() {   //get text cua searchView
			@Override
			public boolean onQueryTextSubmit(String text) {
				
				return true;
			}
			@Override
			public boolean onQueryTextChange(String newText) {
				viewpager.setCurrentItem(TAB_ALL_STORY);
				showViewpagerTab(0);
				if (TextUtils.isEmpty(newText)) {
//			        adapter.getFilter().filter("");
//					mListView.clearTextFilter();
			    } else {
//			        adapter.getFilter().filter(newText.toString());
			    }
				return false;
			}
		});
		
		return super.onCreateOptionsMenu(menu);
	}
	
	
	

	public void showViewpagerTab(int pos) {
		switch (pos) {
		case 0:
			all_story.setVisibility(View.VISIBLE);
			top_view.setVisibility(View.INVISIBLE);
			bookmark.setVisibility(View.INVISIBLE);
			history.setVisibility(View.INVISIBLE);
			break;
		case 1:
			all_story.setVisibility(View.INVISIBLE);
			top_view.setVisibility(View.VISIBLE);
			bookmark.setVisibility(View.INVISIBLE);
			history.setVisibility(View.INVISIBLE);
			break;
		case 2:
			all_story.setVisibility(View.INVISIBLE);
			top_view.setVisibility(View.INVISIBLE);
			bookmark.setVisibility(View.VISIBLE);
			history.setVisibility(View.INVISIBLE);
			break;
		case 3:
			all_story.setVisibility(View.INVISIBLE);
			top_view.setVisibility(View.INVISIBLE);
			bookmark.setVisibility(View.INVISIBLE);
			history.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}
	}
	
	private class StoryPagerAdapter extends FragmentStatePagerAdapter {
		public StoryPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			if (position == TAB_ALL_STORY) {
				return allStoryFragment;
			} else if (position == TAB_TOP_VIEW) {
				return topViewFragment;
			} else if (position == TAB_BOOKMARK) {
				return bookmarkFragment;
			} else if (position == TAB_HISTORY) {
				return historyFragment;

			} else {
				return new Fragment();
			}
		}

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public int getCount() {
			return 4;
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		mDrawerLayout.closeDrawers();
		viewpager.setCurrentItem(TAB_ALL_STORY);
		showViewpagerTab(0);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.activity_main_all_root:
			viewpager.setCurrentItem(TAB_ALL_STORY);
			showViewpagerTab(0);
			break;
		case R.id.activity_main_author_root:
			viewpager.setCurrentItem(TAB_TOP_VIEW);
			showViewpagerTab(1);
			break;
		case R.id.activity_main_bookmark_root:
			viewpager.setCurrentItem(TAB_BOOKMARK);
			showViewpagerTab(2);
			break;
		case R.id.activity_main_history_root:
			viewpager.setCurrentItem(TAB_HISTORY);
			showViewpagerTab(3);
			break;
		default:
			break;
		}
	}

	
	public void testDB(){
//		 AuthorEntity authorEntity = new AuthorEntity(3, "fName", "Hồ biểu Chánh", "aCode");   // co khoa chinh
//		 AuthorService authorService = new AuthorService(MainActivity.this);
//		 authorService.insert_author(authorEntity);
//		 ArrayList<AuthorEntity> list_author = new ArrayList<AuthorEntity>();
//		 list_author = authorService.getAllAuthor();
//		 for (int i = 0; i < list_author.size(); i++) {
//			 LogUtils.e(list_author.get(i).getAuthorID()+"");
//			 LogUtils.e(list_author.get(i).getFName());
//			 LogUtils.e(list_author.get(i).getLName());
//			 LogUtils.e(list_author.get(i).getACode());
//		 }
//
//		 CategoryEntity categoryEntity = new CategoryEntity(3, "Lịch sử", "description");   //co khoa chinh
//		 CategoriesService categoriesService = new
//		 CategoriesService(MainActivity.this);
//		 categoriesService.insert_categories(categoryEntity);
//		 ArrayList<CategoryEntity> list_cate = new
//		 ArrayList<CategoryEntity>();
//		 list_cate = categoriesService.getAllCategories();
//		 for (int i = 0; i < list_cate.size(); i++) {
//			 LogUtils.e(list_cate.get(i).getCatId()+"");
//			 LogUtils.e(list_cate.get(i).getCatName());
//			 LogUtils.e(list_cate.get(i).getDescription());
//		 }
//
//		ChapterEntity chapterEntity = new ChapterEntity(
//				"LSKH0",
//				"Mở đầu",
//				"Cuộc sống của một người xa quê, ở nơi đất khách quê người",
//				"imgLink", "02/04/2013", 1, 1, "statut"); // co khoa chinh
//		 ChapterService chapterService = new
//		 ChapterService(MainActivity.this);
//		 chapterService.insert_chapter(chapterEntity);
//		 ArrayList<ChapterEntity> list_chap = new ArrayList<ChapterEntity>();
//		 list_chap = chapterService.getAllChapter();
//		 for (int i = 0; i < list_chap.size(); i++) {
//			 LogUtils.e(list_chap.get(i).getStoryId()+"");
//			 LogUtils.e(list_chap.get(i).getChapterName());
//			 LogUtils.e(list_chap.get(i).getChapterContent());
//			 LogUtils.e(list_chap.get(i).getImgLink());
//			 LogUtils.e(list_chap.get(i).getSyncDate());
//			 LogUtils.e(list_chap.get(i).getBookmark()+"");
//			 LogUtils.e(list_chap.get(i).getHistory()+"");
//			 LogUtils.e(list_chap.get(i).getStatut());
//		 }
//
//		 ParamEntity paramEntity = new ParamEntity("02/04/2013", "value", "type", "statut");   //khong co khoa chinh
//		 ParamService paramService = new ParamService(MainActivity.this);
//		 paramService.insert_param(paramEntity);
//		 ArrayList<ParamEntity> list_param = new ArrayList<ParamEntity>();
//		 list_param = paramService.getAllParam();
//		 for (int i = 0; i < list_param.size(); i++) {
//			 LogUtils.e(list_param.get(i).getCode());
//			 LogUtils.e(list_param.get(i).getType());
//			 LogUtils.e(list_param.get(i).getValue());
//			 LogUtils.e(list_param.get(i).getStatut());
//		 }
//
//		StoriesEntity storiesEntity = new StoriesEntity("LSKH0",
//				"Ở theo thời", "0/12/2006",
//				"http://readonline.java-tip.com/images/tngh.png",
//				"Lich sử nước ta", 1, 1, 670, 580, "statut"); // co khoa chinh
//		StoriesService storiesService = new StoriesService(MainActivity.this);
//		storiesService.insert_story(storiesEntity);
//		ArrayList<StoriesEntity> list_story = new ArrayList<StoriesEntity>();
//		list_story = storiesService.getAllStory();
//		for (int i = 0; i < list_story.size(); i++) {
//			LogUtils.e(list_story.get(i).getStoryId()+"");
//			LogUtils.e(list_story.get(i).getaCode());
//			LogUtils.e(list_story.get(i).getDescription());
//			LogUtils.e(list_story.get(i).getImgLink());
//			LogUtils.e(list_story.get(i).getName());
//			LogUtils.e(list_story.get(i).getBookmark()+"");
//			LogUtils.e(list_story.get(i).getHistory()+"");
//		}
	}

	public void deleteTableDB() {
		AuthorService authorService = new AuthorService(MainActivity.this);
		authorService.deleteTableAuthor();

		CategoriesService categoriesService = new CategoriesService(MainActivity.this);
		categoriesService.deleteTableCategory();
		
		ChapterService chapterService = new ChapterService(MainActivity.this);
        chapterService.deleteTableChapter();
        
		ParamService paramService = new ParamService(MainActivity.this);
		paramService.deleteTableParam();
		
		StoriesService storiesService = new StoriesService(MainActivity.this);
		storiesService.deleteTableStory();
	}
}

